package com.codeoss.framework.service.impl;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.Statement;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.codeoss.framework.request.InitDBRequest;
import com.codeoss.framework.response.InitDBResponse;
import com.codeoss.framework.service.IInitDBService;
import com.codeoss.framework.util.DBUtil;
import com.codeoss.framework.util.IOUtil;
import com.codeoss.framework.webide.service.IApplicationPageService;

@Service
public class InitDBService implements IInitDBService {
	@Autowired
	private DataSource dataSource;
	@Autowired
	private IApplicationPageService applicationPageService;
	@Value("${framework.db-type}")
	private String dbType;
	@Autowired
	private DBUtil dbUtil;
	@Transactional
	@Override
	public InitDBResponse initDB(InitDBRequest initDBRequest) {
		// TODO Auto-generated method stub
		InitDBResponse initDBResponse = new InitDBResponse();
		
		String sql=getSql();
		Connection connection = DataSourceUtils.getConnection(dataSource);
		Statement stmt=null;
		try {
			stmt=connection.createStatement();
			String sqlArray[]=sql.split(";");
			for(int i=0;i<sqlArray.length;i++) {
			    stmt.execute(sqlArray[i]);
			}
		}catch(Exception e) {
			throw new RuntimeException(e);
		}finally {
			dbUtil.closeStatement(stmt);
			DataSourceUtils.releaseConnection(connection, dataSource);
		}
		
		InputStream is=this.getClass().getClassLoader().getResourceAsStream("com/codeoss/framework/init/base.zip");
		applicationPageService.dataImport(is);
		return initDBResponse;
	}
	
	private String getSql() {
		InputStream is = this.getClass().getClassLoader().getResourceAsStream("com/codeoss/framework/init/"+dbType+"_init.sql");
		BufferedReader reader = null;
		StringBuffer sb = new StringBuffer();
		try {
			reader = new BufferedReader(new InputStreamReader(is));
			String tempStr;
			while ((tempStr = reader.readLine()) != null) {
				sb.append(tempStr);
			}
			reader.close();
		} catch (Exception e) {
             throw new RuntimeException(e);
		}finally {
			IOUtil.closeInputStream(is);
		}
		return sb.toString();
	}
}
